package org.jetlinks.community.publish;

import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.hswebframework.web.id.IDGenerator;
import org.jetlinks.community.constant.RabbitmqConstant;
import org.jetlinks.community.entity.DeviceBizMessage;
import org.jetlinks.community.utils.BizMessageUtil;
import org.jetlinks.community.utils.ErrorUtils;
import org.jetlinks.core.device.DeviceRegistry;
import org.jetlinks.core.event.EventBus;
import org.jetlinks.core.message.CommonDeviceMessage;
import org.jetlinks.core.message.function.FunctionInvokeMessage;
import org.jetlinks.core.message.function.FunctionParameter;
import org.jetlinks.core.message.property.ReadPropertyMessageReply;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Mono;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Component
@Slf4j
public class DeviceMsgPublisher {
    @Autowired
    private DeviceRegistry registry;

    @RabbitListener(queues = RabbitmqConstant.BIZ2IOT_QUEUE)
    public void rabbitmqTopicMsgListener(DeviceBizMessage message, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag){
        try {
            this.publishEvent(BizMessageUtil.buildFunctionInvokeMessage(message));

            channel.basicAck(deliveryTag, false);
        } catch (Exception e) {
            log.error("接收Rabbitmq消息失败 消息内容【{}】",message);
            log.error("接收Rabbitmq消息失败,不在重新放回队列 异常信息",e);
//            try {
//                /**
//                 * deliveryTag:该消息的index
//                 * multiple：是否批量.true:将一次性拒绝所有小于deliveryTag的消息。
//                 * requeue：被拒绝的是否重新入队列
//                 */
//                channel.basicNack(deliveryTag, false, false);
//            } catch (IOException ex) {
//                ex.printStackTrace();
//            }

        }

    }
    public void publishEvent(CommonDeviceMessage deviceMessage){
        Mono.justOrEmpty(deviceMessage)
            .flatMap(item->registry.getDevice(item.getDeviceId()))
            .switchIfEmpty(ErrorUtils.notFound("设备不存在"))
            .flatMapMany(deviceOperator->deviceOperator.messageSender()
            .send(deviceMessage))
            .subscribe((item)->{
                //TODO 数据消费处理
                if(log.isDebugEnabled()){
                    log.debug("biz平台下发指令【{}】,执行结果【{}】",deviceMessage,item);
                }
            },(errorItem)->{
                //TODO 错误消息处理
                log.error("下发指令异常 待处理【{}】",errorItem);
            },()->{
                if(log.isDebugEnabled()){
                    log.debug("下发消息消息完成");
                }
                //TODO 异常消息处理
            });
    }
}

